<template>
  <div class="face-upload">
    <el-container>
      <el-aside>
        <!-- 文件夹列表 -->
        <div class="folder-list">
          <h3>现有库</h3>
          <ul>
            <li
              v-for="folder in folders"
              :key="folder"
              @click="setCurrentFolder(folder)"
            >
              {{ folder }}
            </li>
          </ul>
        </div>

        <!-- 创建文件夹按钮 -->
        <el-button type="primary" @click="showCreateFolderDialog = true"
          >创建文件夹</el-button
        >

        <!-- 创建文件夹对话框 -->
        <el-dialog
          title="创建新文件夹"
          :visible.sync="showCreateFolderDialog"
          @close="resetInput"
        >
          <el-input
            placeholder="输入新文件夹名称"
            v-model="folderName"
            @keyup.enter="createFolder"
          ></el-input>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showCreateFolderDialog = false">取 消</el-button>
            <el-button type="primary" @click="createFolder">确 定</el-button>
          </span>
        </el-dialog>
      </el-aside>

      <el-main>
        <h1>{{ currentFolder }}</h1>
        <!-- 图片预览区 -->
        <div v-if="imageUrl" class="image-preview">
          <img :src="imageUrl" alt="Image Preview" />
        </div>

        <!-- 图片上传 -->
        <el-upload
          class="upload-demo"
          ref="uploader"
          :action="uploadUrl"
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-success="handleSuccess"
          :on-error="handleError"
          :before-upload="beforeUpload"
          :limit="1"
          :file-list="fileList"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
            >上传到服务器</el-button
          >
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件,且不超过2MB
          </div>
          <div v-if="previewImage">
            <img
              :src="previewImage"
              alt="preview"
              style="width: 200px; height: 200px"
            />
          </div>
        </el-upload>

<div class="face-upload">
  <!-- Table goes here -->
  <table class="custom-table" v-if="photos.length > 0">
    <thead>
      <tr>
        <th>ID</th>
        <th>Photo Name</th>
        <th>Photo</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="photo in photos" :key="photo.id">
        <td>{{ photo.id }}</td>
        <td>{{ photo.name }}</td>
        <td><img :src="photo.url" :alt="photo.name" class="photo-img"></td>
      </tr>
    </tbody>
  </table>
  <!-- Display message if no data is available -->
  <div v-else class="no-data">
    暂无数据
  </div>
</div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import axios from "axios";
import { recordOperation } from '@/api/logService'; // 引入日志记录模块

export default {
  name: "FaceUpload",
  data() {
    return {
      folders: [],
      currentFolder: "",
      imageUrl: null,
      folderName: "",
      showCreateFolderDialog: false,
      fileList: [],
      previewImage: "",
      photos: [], // 确保这里声明了 photos
    };
  },
  computed: {
    uploadUrl() {
      return `http://192.168.33.201/api/upload/${this.currentFolder}`;
    },
  },
  created() {
    this.fetchFolders();
  },
  methods: {
    handleFileChange(file, fileList) {
      // 管理文件列表
      this.fileList = fileList.slice(-1); // 保持 fileList 只有最后选择的一个文件
      // 预览文件
      if (file.raw) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.previewImage = e.target.result;
          recordOperation('User selected a file for upload'); // 记录选择文件操作
        };
        reader.readAsDataURL(file.raw);
      }
    },
    handleSuccess(response, file, fileList) {
      console.log("Upload successful:", response);
      console.log("File uploaded:", file);
      console.log("File list:", fileList);
      alert("文件上传成功！");
      this.previewImage = ""; // 清除预览
      recordOperation('User uploaded a file successfully'); // 记录上传文件操作
    },
    handleError(err, file, fileList) {
      console.error("Upload failed:", err);
      console.log("File:", file);
      console.log("File list:", fileList);
      alert("文件上传失败！");
      recordOperation('User failed to upload a file'); // 记录上传失败操作
    },
    beforeUpload(file) {
      const isJPGorPNG =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLimitSize = file.size / 1024 / 1024 < 2;
      if (!isJPGorPNG) {
        this.$message.error("上传文件只能是 JPG 或 PNG 格式!");
        recordOperation('User attempted to upload a non-JPG/PNG file'); // 记录无效文件类型操作
        return false;
      }
      if (!isLimitSize) {
        this.$message.error("上传文件大小不能超过 2MB!");
        recordOperation('User attempted to upload a file exceeding size limit'); // 记录文件超大小限制操作
        return false;
      }
      return isJPGorPNG && isLimitSize;
    },
    submitUpload() {
      if (this.$refs.uploader && this.fileList.length > 0) {
        this.$refs.uploader.submit(); // 触发上传
        recordOperation('User submitted a file for upload'); // 记录提交上传操作
      } else {
        this.$message.error("请先选择文件!");
        recordOperation('User attempted to submit without selecting a file'); // 记录未选择文件的提交操作
      }
    },
    createFolder() {
      axios
        .post(`http://192.168.33.201/api/create_folder`, {
          folderName: this.folderName,
        })
        .then((response) => {
          console.log("Folder created successfully:", response.data);
          this.folders.push(this.folderName);
          this.$message("Folder created successfully");
          this.resetInput();
          recordOperation(`User created a new folder: ${this.folderName}`); // 记录创建文件夹操作
        })
        .catch((error) => {
          console.error("Failed to create folder:", error);
          this.$message.error("Failed to create folder: " + error.message);
          recordOperation(`User failed to create a new folder: ${error.message}`); // 记录创建文件夹失败操作
        });
    },
    resetInput() {
      this.folderName = "";
      this.showCreateFolderDialog = false;
    },
    fetchFolders() {
      axios
        .get("http://192.168.33.201/api/list_folders")
        .then((response) => {
          this.folders = response.data.folders;
          recordOperation('User fetched the list of folders'); // 记录获取文件夹列表操作
        })
        .catch((error) => {
          console.error("Error fetching folders:", error);
          alert("Failed to fetch folders!");
          recordOperation(`User failed to fetch the list of folders: ${error.message}`); // 记录获取文件夹列表失败操作
        });
    },
    setCurrentFolder(folder) {
      this.currentFolder = folder;
      this.fetchPhotos(folder); // Fetch photos when a folder is selected
      recordOperation(`User selected folder: ${folder}`); // 记录选择文件夹操作
    },
    fetchPhotos(folderName) {
      axios
        .get(`http://192.168.33.201/api/photos/${folderName}`)
        .then((response) => {
          this.photos = response.data.map((photo, index) => ({
            id: index + 1,
            name: photo,
            url: `http://192.168.33.201/api/photos/${folderName}/${photo}`,
          }));
          recordOperation(`User fetched photos from folder: ${folderName}`); // 记录获取照片操作
        })
        .catch((error) => {
          console.error("Error fetching photos:", error);
          recordOperation(`User failed to fetch photos from folder: ${folderName}`); // 记录获取照片失败操作
        });
    },
  },
};
</script>

<style scoped>
.el-upload__tip {
  color: #aeaeae;
  font-size: 16px;
}
.el-aside {
  border: 1px solid #ccc;
  background-color: #3b5381;
  height: 80vh;
  margin-right: 20px;
}
.el-main {
  border: 1px solid #ccc;
  background-color: #3b5381;
  height: 80vh;
}
.folder-list {
  background-color: #21304b; /* 背景颜色 */
  padding: 20px; /* 内边距 */
  border-radius: 8px; /* 边框圆角 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  margin: 20px; /* 外边距 */
  color: #fff; /* 文本颜色 */
}

.folder-list h3 {
  color: #fff; /* 标题颜色 */
  margin-bottom: 10px; /* 标题下边距 */
}

.folder-list ul {
  list-style: none; /* 移除列表项目的标记 */
  margin: 0; /* 移除默认边距 */
  padding: 0; /* 移除默认内边距 */
}

.folder-list li {
  padding: 10px 15px; /* 列表项内边距 */
  border: 1px solid #ddd; /* 边框 */
  border-radius: 5px; /* 边框圆角 */
  margin-bottom: 8px; /* 项目间距 */
  cursor: pointer; /* 鼠标样式 */
  transition: background-color 0.3s, box-shadow 0.3s; /* 过渡效果 */
}

.folder-list li:hover {
  background-color: #e9e9e9; /* 鼠标悬停背景色 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); /* 鼠标悬停阴影效果 */
}

.folder-list li:active {
  background-color: #ddd; /* 鼠标点击时的背景色 */
}
.face-upload {
  display: flex;
  justify-content: space-between;
  padding: 20px;
}
.image-preview img {
  width: 200px;
  height: 200px;
  object-fit: contain;
  border: 1px solid #ccc;
}
.no-data {
  text-align: center;
  padding: 20px;
  background-color: #21304b;
  color: #ffffff;
  font-size: 30px;
  border-radius: 4px;
  margin: 20px auto; /* Centering */
  width: 50%; /* Or any other suitable width */
}

.custom-table {
  width: 100%;
  border-collapse: collapse;
  background-color: #21304b;
  color: white;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  border-radius: 4px;
  overflow: hidden;
}

.custom-table th, .custom-table td {
  padding: 10px; /* 单元格内边距 */
  border: 1px solid #324a5e; /* 单元格边框 */
}

.custom-table th {
  background-color: #324a5e; /* 表头背景色 */
}

.custom-table td {
  vertical-align: middle; /* 垂直居中 */
}

.photo-img {
  width: 100px; /* 设置图片宽度 */
  height: 100px; /* 设置图片高度 */
  object-fit: cover; /* 覆盖尺寸以填满容器 */
  border-radius: 4px; /* 图片圆角 */
}

.photo-img:hover {
  transform: scale(1.1); /* 鼠标悬停时放大图片 */
  transition: transform 0.3s ease-in-out; /* 过渡效果 */
}
</style>
